package com.natalia.excel.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.google.gson.Gson;
import com.natalia.excel.entity.ImportModel;
import com.natalia.excel.listener.normal.GenericExcelListener;
import com.natalia.excel.listener.normal.GenericExcelResult;
import com.natalia.excel.listener.sync.SyncService;
import com.natalia.excel.response.Result;
import com.natalia.excel.service.ImportService;
import com.natalia.excel.utils.EasyExcelValidaHelper;
import com.natalia.excel.validate.file.FileType;
import com.natalia.excel.validate.file.MultipartFileVerify;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @Author yang
 **/
@Slf4j
@Validated
@RestController
@RequestMapping("/import")
@RequiredArgsConstructor
public class ImportController {

    private final SyncService syncService;

    /**
     *  使用监听导入数据
     * @param file
     */
    @PostMapping({"/normal"})
    @Transactional(rollbackFor = Exception.class)
    public Result normal(@RequestParam("file") @MultipartFileVerify(value = {FileType.XLSX,FileType.XLS},nullable = true)
                           MultipartFile file){
        GenericExcelResult result = new GenericExcelResult();
        try {
              EasyExcelFactory.read(file.getInputStream(),ImportModel.class,
                              new GenericExcelListener<>(ImportService.class,"batchInsert",result,ImportModel.class)).sheet(1).doRead();
              log.info(new Gson().toJson(result));
            return new Result(result);
          }catch (Exception e){
              log.info("import error : {}", ExceptionUtils.getStackTrace(e));
              throw new RuntimeException(e);
          }
    }

    /**
     * 读取所有数据
     * @param file
     * @return
     */
    @PostMapping({"/sync"})
    @Transactional(rollbackFor = Exception.class)
    public Result sync(@RequestParam("file") @MultipartFileVerify(value = {FileType.XLSX,FileType.XLS},nullable = true)
                         MultipartFile file) {
        try {
            SyncReadListener syncReadListener = new SyncReadListener() {
                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    EasyExcelValidaHelper.invokeHeadMap(headMap,ImportModel.class);
                }
            };
            List<ImportModel> dataList = EasyExcelFactory.read(file.getInputStream(),
                    ImportModel.class, syncReadListener).head(ImportModel.class).sheet().doReadSync();
            syncService.sync(dataList);
        }catch (Exception e){
            log.info("import error : {}", ExceptionUtils.getStackTrace(e));
            throw new RuntimeException(e);
        }
       return null;
    }

}
